const { app, BrowserWindow, BrowserView, protocol, ipcMain, globalShortcut, dialog, shell} = require('electron')
const protocolX = require('./main/protocol');
const X6Core = require('./main/X6Core');
const path = require('path')
const AppVersion = require('./main/api/app');
const envConfig = require('./main/config/env');

protocolX();

const createWindow = () => {

  // X6Core.testChomrDriver();

  const win = new BrowserWindow({
      width: 1024,
      height: 768,
      webPreferences: {
          preload: path.join(__dirname, 'preload.js'),
          webSecurity: false,
          nodeIntegration: true
      },
      // // 隐藏窗口
      // show: false,
      // // 背景透明
      // transparent: true,
      // // mac标题栏
      // titleBarStyle: 'hiddenInset',
      // 隐藏标题栏
      frame: false
  })

  // 创建View遮罩
  const view = new BrowserView({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      webSecurity: false,
      nodeIntegration: true
  }});
  win.setBrowserView(view)
  view.setBounds({ x: 0, y: 0, width: 1024, height: 768 })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
      win.loadFile('./dist/index.html')
      view.webContents.loadFile('loading.html')
      if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
      view.webContents.loadFile('./loading.html')
      win.loadURL('xrpa://dist/index.html');
    //   win.webContents.openDevTools({mode:'detach'})
    //   view.webContents.openDevTools({mode:'detach'})
  }

  // 显示Loading
  let showTime = null;
  view.webContents.on('dom-ready', () => {
      console.log('dom-ready', new Date())
      win.show()
      showTime = new Date().getTime();
  })

  // 关闭loading
  ipcMain.on('stop-loading-main', () => {
    let stopTime = new Date().getTime();
    let diff = stopTime - showTime;
    console.log('showTime', showTime);
    console.log('stopTime', stopTime);
    console.log('diff time', diff);
    if(diff>1500){ // 启动页面展示时间已超过3秒，则直接进入应用
        console.log('diff>2000')
        win.removeBrowserView(view)
    }else{
        // 启动时间未超过3秒， 需要继续等待
        let wait = 1500-diff;
        console.log('wait', wait)
        setTimeout(() => {
            win.removeBrowserView(view)
        }, wait);
    }
  })

  X6Core.initHandler(win);
  AppVersion.checkUpdate().then(res=>{
      console.log('AppVersion.checkUpdate()', res);
      let version = parseInt(res.data.version);
      if(version > envConfig.appVersion){
        let ret = alert(res.data.content);
        console.log('click ret', ret);
        if(ret == 0) {
          // 去更新, 打开浏览器
          console.log('res.data.link', res.data.link);
          shell.openExternal(res.data.link);
        }else{
          // 知道了
        }
      }
  });
}

app.whenReady().then(() => {
    protocolX.createProtocol(app, 'xrpa')
    protocolX.setDefaultProtocol(app, 'xrpa')
    createWindow()
})
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})


app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})


let canQuit = false;
app.on('close', (event) => {
    if (!canQuit) {
      event.preventDefault();
    }
});

app.on('ready', () => {
    globalShortcut.register('CommandOrControl+Alt+K', () => {
      dialog.showMessageBox({
        type: 'info',
        title: '温馨提示',
        message: '确认要退出应用吗?',
        buttons: ['是的','点错了~']
      }).then((ret)=>{
        console.log('you chose',ret.response)
        if(ret.response===0){
            canQuit=true;
            app.quit();
        }
      })
    })
    globalShortcut.register('Command+Q', () => {
        dialog.showMessageBox({
          type: 'info',
          title: '温馨提示',
          message: '确认要退出应用吗?',
          buttons: ['是的','点错了~']
        }).then((ret)=>{
          console.log('you chose',ret.response)
          if(ret.response===0){
              canQuit=true;
              app.quit();
          }
        })
      })
})

alert = function(str){
  var options = {
    type: 'info',
    buttons: ["去更新", "知道了"],
    defaultId: 0,
    cancelId:0,
    detail:str,
    message: '提示'
  }
  let ret = dialog.showMessageBoxSync(null,options);
  console.log("click at", ret);
  return ret;
}